
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

#define MAX_UPLOAD_BYTES 1000000

char *
read_file(char *filename, int *nbytes)
{
  char *cp;
  int status;
  struct stat sb;
  int fd = open(filename, O_RDONLY);
  if (fd < 0) {
    return NULL;
  }

  status = fstat(fd, &sb);
  if (status < 0) {
    exit(10);
  }

  if (sb.st_size <= 0) {
    exit(11);
  }
  if (sb.st_size > MAX_UPLOAD_BYTES) {
    exit(12);
  }
  cp = malloc(sb.st_size + 1);
  if (cp == NULL) {
    exit(13);
  }

  status = read(fd, cp, sb.st_size);
  if (status != sb.st_size) {
    exit(14);
  }

  cp[sb.st_size] = 0;
  *nbytes = sb.st_size;
  return cp;
}

int
write_file(char *filename, char *cp, int nbytes)
{
  int fd = open(filename, O_WRONLY|O_EXCL|O_CREAT, 0755);
  int count;
  if (fd == -1) {
    exit(20);
  }
  count = write(fd, cp, nbytes);
  if (count == -1) {
    exit(21);
  }
  if (count != nbytes) {
    exit(22);
  }
  return count;
}

int
skelmain(char *input, char *inter, char *output)
{
  char *cp, *cp2;
  int nbytes;
  int status;
  cp = read_file(input, &nbytes);
  write_file(inter, cp, nbytes);
  free(cp);
  cp = read_file(inter, &nbytes);
  write_file(output, cp, nbytes);
  free(cp);
  return 0;
}


int
write_hello(char *filename)
{
  char *hi = "hello\n";
  return write_file(filename, hi, strlen(hi));
}


int
main(int argc, char **argv)
{
  char *input = argv[1];
  char *inter = argv[2];
  char *output = argv[3];
  char *comment = argv[4];
  char *level = argv[5];
  int status;

  if (argc != 6) {
    exit(1);
  }

  (void)write_hello(comment);

  status = skelmain(input, inter, output);
  exit(status);
}
